<template>
    <el-select
        v-model="recipients"
        multiple
        filterable
        ref="selectRef"
        allow-create
        size="middle"
        default-first-option
        :reserve-keyword="false"
        @keydown="handleKeyDown"
        @focus="current = null"
        :placeholder="placeholder"
    >
        <!-- <el-option v-for="user in recipList" :value="user.id" :label="user.name" :key="user.id"></el-option> -->
         <template #tag>
            <tag v-for="item in recipients" @select="handlerSelect(item)" :selected="current === item" :content="item" />
         </template>
    </el-select>
</template>
<script setup>
import { onMounted, watch, onUnmounted, ref } from 'vue';
import Tag from './tag.vue';

const props = defineProps({
    modelValue: {
        type: Object,
        default: [],
    },
    placeholder: {
        type: String,
        default: "请输入",
    },
});

const emit = defineEmits(['update:modelValue']);

const recipients = ref(props.modelValue);
const selectRef = ref();
const current = ref();

// 监听 value 属性变化
watch(() => props.modelValue, (newValue, oldVal) => {
    if (JSON.parse(newValue) !== JSON.parse(recipients.value)) {
        recipients.value = newValue;
    }
});

const handleKeyDown = (e) => {
  // 监听退格键
  if (e.key === 'Backspace' || e.keyCode === 8) {
    if (current.value) {
        e.stopPropagation(); // 阻止事件冒泡
        recipients.value = recipients.value.filter(item => item !== current.value);
        current.value = null;
        emit('update:modelValue', recipients.value);
    }
  }
};

const handlerSelect = (item) => {
    current.value = item;
    if (selectRef.value) {
        selectRef.value.blur();
    }       
};

</script>
<style scoped  lang="scss" >
</style>